package com.example.springboot.config.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoggingInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 在请求处理之前记录日志，可以获取请求参数等信息
        String requestURI = request.getRequestURI();
        String method = request.getMethod();
        String queryString = request.getQueryString();
        // 可以根据需要记录更多信息

        System.out.println("Request: " + method + " " + requestURI + (queryString != null ? "?" + queryString : ""));
        // 记录日志到文件
        // logger.info("Request: " + method + " " + requestURI + (queryString != null ? "?" + queryString : ""));

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 在请求处理之后记录日志，可以获取响应结果等信息
        // 可以根据需要记录更多信息

        System.out.println("Response: " + response.getStatus());
        // 记录日志到文件
        // logger.info("Response: " + response.getStatus());
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 请求完成后的清理工作，可以记录异常信息等
        // 可以根据需要记录更多信息
    }
}
